<!--
 * @Descripttion: 
 * @version: 
 * @Author: wtzhang
 * @Date: 2021-07-21 16:09:52
 * @LastEditors: wtzhang
 * @LastEditTime: 2021-07-21 16:55:46
-->
<template>
  <div class="customRef2">
    <h3 class="title">customRef2</h3><hr>
    <ul v-for="item in resData" :key="item">
      <li>{{item.name}}--{{item.message}}---{{item.date}}</li>
    </ul>
  </div>
</template>

<script lang="ts">
import { customRef, defineComponent } from 'vue'
// 自定义封装异步请求api 的 ref (由于setup只能是同步执行)
function useCustomApiRef<T>(value){
  return customRef((track, trigger) => {
    // 发起请求
    fetch(value).then((res) => {
      return res.json()
    }).then((data) => {
      // console.log(data.data.list);
      value = data.data.list
      trigger()
    }).catch(e => {
      console.log(e);
    })
    return {
      get(){
        track()
        return value
      },
      set(val: T){
        trigger()
        value = val
      }
    }
  })
}
export default defineComponent ({
  name: 'customRef2', 
  setup(){
    let resData = useCustomApiRef('http://120.77.35.150:3000/api/list')
    console.log(resData);
    
    return {
      resData
    }
  }
})
</script>

<style>
  .customRef2 {
    padding: 16px;
  }
</style>